<?php

namespace backend\controllers;

use backend\models\organization\ApplyModel;
use bc\controller\BackendController;
use bc\model\SpreadModel;
use bc\model\GradeModel;
use bc\util\Util;
use yii;
use bc\util\backend\Page;
use bc\ar\MActiveRecord;
use bc\wx\OAuth;
use bc\wx\Auth;
use bc\wx\User;

class SpreadController extends BackendController
{
    public function actionIndex()
	{
        $model = new SpreadModel();

        $wx_name = $this->get('wx_name', '');
        if($wx_name != '')
        {
            $params = "`wx_name` LIKE '%{$wx_name}%'";
        }else{
            $params = '1 = 1 ';
        }

        $sort_num = $this->get('sort_num', '');
        $sort_time = $this->get('sort_time', '');

        if(($sort_num == '') && ($sort_time == '')){
            $sort = ' create_time desc';
        }elseif($sort_num == ''){
            if($sort_time == 'desc'){
                $sort = ' create_time desc';
            }elseif($sort_time == 'asc'){
                $sort = 'create_time asc';
            }else{
                $sort = 'create_time desc';
            }
        }elseif($sort_time == ''){
            if($sort_num == 'desc'){
                $sort = ' success_num desc';
            }elseif($sort_num == 'asc'){
                $sort = 'success_num asc';
            }else{
                $sort = 'success_num desc';
            }
        }else{
            $sort = ' create_time,success_num desc';
        }

        $start_time_str = $this->get('start_time', '');
        $end_time_str = $this->get('end_time', '');
        $start_time = $start_time_str ? strtotime($start_time_str) : '';
        $end_time = $end_time_str ? strtotime($end_time_str) : '';
        if($start_time != '')
        {
            $params = $params . " and `create_time` >= '{$start_time}'";
        }

        if($end_time != '')
        {
            $end_time+=60*60*24;
            $params = $params . " and `create_time` <= '{$end_time}'";
        }

        //获取等级
        $gradeM = new GradeModel();
        $where='1 = 1 ';
        $gradeList = $gradeM->getList($where);
        $gradeArr=array();
        foreach($gradeList as $k=>$v)
        {
            $gradeArr[$v["grade_id"]]=$v["grade_cn"];
        }


        $page = $this->get('page', 1);
        $model->sort=$sort;
        $list = $model->getList($params, $page, self::PAGE_SIZE);
        $total = $model->getTotal($params);
        $pagination = new Page($total, self::PAGE_SIZE);

        $view['gradearr']=$gradeArr;
        $view['list'] = $list;
        $view['wx_name'] = $wx_name;
        $view['pagination'] = $pagination;
        $view['start_time'] = $start_time_str;
        $view['end_time'] = $end_time_str;
		return $this->render('index',$view);
	}

    public function actionAdopt()
    {
        $spread_id = $this->get('id');
        $model = new SpreadModel();
        $model->autoId = 'spread_id';
        $row=$model->getRowById($spread_id);
        $data['row']= $row;
        return $this->render('adopt',$data);
    }

    /*
     *审核通过
     * */
    public function actionAdoptpass()
    {
        $spread_id = $this->get('id');
        $mobile = $this->get('mobile');
        $email =  $this->get('email');
        $sh_describe =  $this->get('sh_describe');
        $distributor = $this->get('distributor');
        $data['mobile'] = $mobile;
        $data['email'] = $email;
        $data['sh_describe'] = $sh_describe;
        $data['sh_time'] = time();
        $data['distributor'] = $distributor;
        $model = new SpreadModel();
        $model->modify($data,$spread_id);
        if($distributor == 3){
            $output['msg'] = '审核通过！';
        }else{
            $output['msg'] = '审核不通过！';
        }

        $output['url'] = '/spread/index';
        $this->forward($output);
    }

    /*
     *查看审核情况
     * */
    public function actionInfo()
    {
        $spread_id = $this->get('id');
        $model = new SpreadModel();
        $model->autoId = 'spread_id';
        $row=$model->getRowById($spread_id);
        $data['row']= $row;
        return $this->render('info',$data);
    }

    /*
     *查看审核情况
     * */
    public function actionEdit()
    {
        $spread_id = $this->get('id');
        $model = new SpreadModel();
        $model->autoId = 'spread_id';
        $row=$model->getRowById($spread_id);
        $data['row']= $row;
        return $this->render('edit',$data);
    }

    /*
     * 保存
     * */
    public function actionSave()
    {
        $spread_id = $this->get('id');
        $mobile = $this->get('mobile');
        $email =  $this->get('email');
        $sh_describe =  $this->get('sh_describe');
        $data['mobile'] = $mobile;
        $data['email'] = $email;
        $data['sh_describe'] = $sh_describe;
        $model = new SpreadModel();
        $model->modify($data,$spread_id);
        $output['msg'] = '修改成功！';
        $output['url'] = '/spread/index';
        $this->forward($output);
    }

    /*
     * 我的二维码
     */
    public function actionQrcode()
    {
        $spread_id = $this->get('id');
        $model = new SpreadModel();
        $model->autoId='spread_id';
        $spRow=$model->getRowById($spread_id);
        $data ['openid'] = $spRow ['openid'];
        // $data['openid'] = 'o8eQSwg3jMbMAD8yE5cx_j9K6E30';
        if(empty($data ['openid'])){
            echo "错误，该用户没有openid";
            die();
        }

        $dao = new MActiveRecord ();
        $sql = "select * from ecs_users left join  wxch_qr on ecs_users.user_id = wxch_qr.binduser where scene like '%推广%'  and wxid='" . $data ['openid'] . "'";
        $row = $dao->getDb ()->createCommand ( $sql )->queryOne ();
        $row['wx_name']=$spRow['wx_name'];
        $view['row'] = $row;
        return $this->render ( 'qrcode', $view );
    }

    /*
    *更新用户基本信息
    */
    public function actionUpdateuserinfo()
    {
        set_time_limit(0);
        $appid = $this->wechat()->appid;
        $secret = $this->wechat()->secret;

        $where = '1 = 1 ';
        //获取spread表中的所有信息
        $spreadM = new SpreadModel();

        $spreadT = $spreadM->getTotal($where);
        $spreadList = $spreadM->getList($where);
        $auth = new Auth($appid, $secret);
        $accessToken = $auth->accessToken;
        $user = new User();

        $size=0;
        $tag=0;
        $data['user_list']=array( );
        foreach($spreadList as $item) {
            $datatemp=array(
                "openid" => $item['openid'],
                "lang" => "zh-CN"
            );
            array_push($data['user_list'],$datatemp);

            if(++$size >=100 || ++$tag == count($spreadList)){

                $dataj = json_encode($data);
                $info = $user->getBatchUserInfo($accessToken, $dataj);
                if(!empty($info)){
                    $this->updataUserInfo($info['user_info_list']);
                }
                $data['user_list']=array();
            }
        }

        $rdate = array('result'=>1);

        echo json_encode($rdate);
    }

    private function updataUserInfo($dataArr)
    {
        $spreadM = new SpreadModel();
        foreach($dataArr as $item){
            $where =  array(
                'openid'=>$item['openid']
            );
            if($item['subscribe'] == 1) {
                $data = array(
                    'wx_name' => Util::replace_emoji($item['nickname']),
//                'wx_name' => $item['nickname'],
                    'headimgurl' => $item['headimgurl']
                );

                $spreadR = $spreadM->getRow($where);
                $spreadM->modify($data, $spreadR['spread_id']);
                unset($where);
                unset($data);
            }
        }
    }

    /*
     * 模板消息测试
     * */
    public function actionTousermag()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=Clq34iOsGN7Mjq6zjsyEuEXhOSJlht2GR4iJNJC8CUPXfVTrolbsFj0UTQzJ0n1oer_Sy_MKcNrRdMZFQo02SuFuy8naTgjF6-ZjPy_UR_qWV8qexYokvEV5pfzNdSCcBVLbAAAHBR';


        $post_msg = '{
       "touser":"o8eQSwuio9ktqZPqYwtGHSXFY7YA",
       "msgtype":"news",
       "news":{
           "articles": [
            {
                "title":"'.'测试领奖吧'.'",
                "description":"'.'内容'.'",
                "url":"'.'http://www.zhishimama.com'.'",
                "picurl":"'.'www.zhishimama.com/img/logo.png'.'"
            }
            ]
       }
   }';

        $res = Util::httpPost($url, $post_msg);

        print_r($res);

    }

    /*
 * 模板消息测试
 * */
    public function actionTest()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=Clq34iOsGN7Mjq6zjsyEuEXhOSJlht2GR4iJNJC8CUPXfVTrolbsFj0UTQzJ0n1oer_Sy_MKcNrRdMZFQo02SuFuy8naTgjF6-ZjPy_UR_qWV8qexYokvEV5pfzNdSCcBVLbAAAHBR';


        $post_msg = '{
       "touser":"o8eQSwuio9ktqZPqYwtGHSXFY7YA",
       "msgtype":"news",
       "news":{
           "articles": [
            {
                "title":"'.'测试领奖吧'.'",
                "description":"'.'内容'.'",
                "url":"'.'http://www.zhishimama.com'.'",
                "picurl":"'.'www.zhishimama.com/img/logo.png'.'"
            }
            ]
       }
   }';

        $res = Util::httpPost($url, $post_msg);

        print_r($res);

    }
}

